package com.jiuli.liping.service.impl;

import com.jiuli.liping.dao.*;
import com.jiuli.liping.service.WeiXinService;
import com.jiuli.liping.test.MyAsyncTask;
import com.jiuli.liping.util.DateUtils;
import com.jiuli.liping.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.jiuli.liping.service.ProductOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Author zyl
 * Date  2020-03-25
 */
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
    @Autowired
    private ProductOrderDao productOrderDao;

    @Autowired
    private ProductDao productDao;
    @Autowired
    private MoveHisDao moveHisDao;
    @Autowired
    private UserlistDao userlistDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private CommodityDao commodityDao;

    @Autowired
    private WeiXinService weiXinService;
    
    @Override
    public ProductOrder get(String id){
        return productOrderDao.get(id);
    }
    
    @Override
    public List<ProductOrder> findList(ProductOrder productOrder) {
        return productOrderDao.findList(productOrder);
    }
    
    @Override
    public List<ProductOrder> findAllList() {
        return productOrderDao.findAllList();
    }
    
    @Override
    public int insert(ProductOrder productOrder) {
        return productOrderDao.insert(productOrder);
    }
    
    @Override
    public int insertBatch(List<ProductOrder> productOrders){
        return productOrderDao.insertBatch(productOrders);
    }
    
    @Override
    public int update(ProductOrder productOrder) {
        return productOrderDao.update(productOrder);
    }
    
    @Override
    public int delete(ProductOrder productOrder) {
        //取消订单，库存回复
        //List<ProductOrder> prolist = productOrderDao.findAllListByNum(productOrder);
        /*for (ProductOrder pro : prolist) {
            Product pr2 = new Product();
            pr2.setProductNum(pro.getFbk1());
            Product pr3 = productDao.getProductByProductNum(pr2);//商品资料
            int number = Integer.parseInt(pr3.getFbk3())+Integer.parseInt(pro.getAmount());//现有数量
            pr2.setFbk3(number+"");
            int aa = productDao.updateProductByNumber(pr2);
        }*/
        productOrder.setOrderStatus("2");
        return productOrderDao.updateStatusByNum(productOrder);
    }

    @Override
    @Transactional
    public Message submitOrder(ProductOrder productOrder) throws InterruptedException{
        Message me = new Message();
        //创建订单
        Timestamp curDate = new Timestamp(System.currentTimeMillis());
        long str = System.currentTimeMillis();
        productOrder.setOrderNum("DD"+str);
        if(productOrder.getProductOrderList().size()>0) {
            for (ProductOrder pro : productOrder.getProductOrderList()) {
                //商品现有库存
                Commodity commodity = new Commodity();
                commodity.setCommodityNumber(pro.getFbk1());
                Commodity commodity2 = commodityDao.selectOneCommodity(commodity);
                String amount = productDao.findSumAmount(pro.getFbk1());
                String realAmount = productOrderDao.findSumRealAmount(pro.getFbk1());
                if(amount == null){ amount="0";}if(realAmount == null){ realAmount="0";}
                int fbk2 = Integer.parseInt(amount)-Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(realAmount);

                //校验库存是否已经下架
                int g = commodityDao.jyProductStatus(pro.getFbk1());
                if(g == 0){
                    me.setFlag(-1+"");
                    me.setMessage(commodity2.getCommodityFatherName()+":已经下架");
                    return me;
                }

                if(fbk2 < Integer.parseInt(pro.getAmount())){
                    me.setFlag(-1+"");
                    me.setMessage("商品库存不足");
                    return me;
                }

                pro.setTradeName(commodity2.getCommodityFatherName());//品名
                pro.setSupplier(commodity2.getSupplier());//供应商

                Userlist user = new Userlist();
                user.setUserNum(productOrder.getUserNum());
                Userlist us = userlistDao.findInfoByUserNum(user);

                pro.setRecipientsDepartment(us.getDepartmentDescribe());//领用部门
                pro.setOrderNum(productOrder.getOrderNum());
                pro.setFbk2(productOrder.getUserNum());
                pro.setCreateUser(us.getUserName());//创建人
                pro.setCreateTime(curDate);
                pro.setOrderStatus("1");//订单状态默认为1
            }
            int a = productOrderDao.insertBatch(productOrder.getProductOrderList());

            if(a>0) {
                for (ProductOrder pro2 : productOrder.getProductOrderList()) {
                    //删除购物车已勾选的数据
                    ShoppingCart sh = new ShoppingCart();
                    sh.setShoppingCartId(pro2.getShoppingCartId());
                    shoppingCartDao.delete(sh);

                    //提交订单后改变商品库存
                    /*Product pr2 = new Product();
                    pr2.setProductNum(pro2.getFbk1());
                    Product pr3 = productDao.getProductByProductNum(pr2);//商品资料
                    int number = Integer.parseInt(pr3.getFbk3())-Integer.parseInt(pro2.getAmount());//现有数量
                    pr2.setFbk3(number+"");
                    a = productDao.updateProductByNumber(pr2);*/
                }
            }
            me.setFlag("1");
            me.setMessage("success");
            me.setOrderNum("DD"+str);
            return me;
        }else{
            me.setFlag(0+"");
            me.setMessage("failed");
            return me;
        }
    }

    @Override
    public List<ProductOrder> findAllListByName(ProductOrder productOrder) {
        productOrder.setOrderStatus("2");
        List<ProductOrder> list = productOrderDao.findAllListByName(productOrder);
        for (ProductOrder pro : list) {
            pro.setCreateTimeToString(DateUtils.getTime(pro.getCreateTime()));//时间转换
            double priceAll=0;
            for (ProductOrder pro2: pro.getProductOrderList()) {
                //找到图片
                List<Photograph> list1 = commodityDao.findAllListByPhotograph(pro2.getFbk1());
                if(list1!=null) {
                    pro2.setPicture(list1.get(0).getPhotographUrl());
                }
                //计算价格
                //找到商品价格
                Commodity commodity = new Commodity();
                commodity.setCommodityNumber(pro2.getFbk1());
                Commodity commodity2 = commodityDao.selectOneCommodity(commodity);

                //属性拼起来
                CommodityServiceImpl co = new CommodityServiceImpl();
                String propertyname = co.getPropertyNameTo(commodity2);
                pro2.setPropertyAll(propertyname);
                //Product pr = new Product();
                //pr.setProductNum(pro2.getFbk1());
                //Product newpr = productDao.getProductByProductNum(pr);
                double price = (Integer.parseInt(pro2.getAmount()) * Double.parseDouble(commodity2.getSalesPrice()));
                priceAll+=price;
                pro2.setMarketPrice(commodity2.getSalesPrice());
                pro2.setPrice(price+"");
            }
            pro.setPrice(priceAll+"");
        }
        return list;
    }

    @Override
    @Transactional
    public Message submitOrderOne(ProductOrder productOrder) throws InterruptedException{
        Message me = new Message();
        //创建订单
        Timestamp curDate = new Timestamp(System.currentTimeMillis());
        long str = System.currentTimeMillis();
        productOrder.setOrderNum("DD"+str);

        //商品现有库存
        Commodity commodity = new Commodity();
        commodity.setCommodityNumber(productOrder.getFbk1());
        Commodity commodity2 = commodityDao.selectOneCommodity(commodity);
        String amount = productDao.findSumAmount(productOrder.getFbk1());
        String realAmount = productOrderDao.findSumRealAmount(productOrder.getFbk1());
        if(amount == null){ amount="0";}if(realAmount == null){ realAmount="0";}
        int fbk2 = Integer.parseInt(amount)-Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(realAmount);

        if(fbk2 < Integer.parseInt(productOrder.getAmount())){
            me.setFlag(-1+"");
            me.setMessage("商品库存不足");
            return me;
        }

        productOrder.setTradeName(commodity2.getCommodityFatherName());//品名
        productOrder.setSupplier(commodity2.getSupplier());//供应商

        Userlist user = new Userlist();
        user.setUserNum(productOrder.getUserNum());
        Userlist us = userlistDao.findInfoByUserNum(user);

        productOrder.setRecipientsDepartment(us.getDepartmentDescribe());//领用部门
        productOrder.setOrderNum(productOrder.getOrderNum());
        productOrder.setFbk2(productOrder.getUserNum());
        productOrder.setCreateUser(us.getUserName());//创建人
        productOrder.setCreateTime(curDate);
        productOrder.setOrderStatus("1");//订单状态默认为1

        int a = productOrderDao.insert(productOrder);

        /*if(a>0) {
            //提交订单后改变商品库存
            Product pr2 = new Product();
            pr2.setProductNum(productOrder.getFbk1());
            Product pr3 = productDao.getProductByProductNum(pr2);//商品资料
            int number = Integer.parseInt(pr3.getFbk3())-Integer.parseInt(productOrder.getAmount());//现有数量
            pr2.setFbk3(number+"");
            a = productDao.updateProductByNumber(pr2);
        }*/
        me.setFlag(a+"");
        me.setMessage("success");
        me.setOrderNum("DD"+str);
        return me;
    }

    @Override
    public List<ProductOrder> findProductOrderList(ProductOrder productOrder) {
        String orderStatus = "4";
        List<ProductOrder> list =new ArrayList<>();
        if(productOrder.getSf2() == null) {
            list = productOrderDao.findProductOrderList(orderStatus);
        }else if("1".equals(productOrder.getSf2())){
            list = productOrderDao.findProductOrderList3(orderStatus);
        }else{
            list = productOrderDao.findProductOrderList2(orderStatus);
        }
        for (ProductOrder pro: list) {
            for (ProductOrder pro2: pro.getProductOrderList()) {
                Commodity commodity = new Commodity();
                commodity.setCommodityNumber(pro2.getFbk1());
                Commodity commodity2 = commodityDao.selectOneCommodity(commodity);
                //属性拼接
                CommodityServiceImpl co = new CommodityServiceImpl();
                String spsx = co.getPropertyNameTo(commodity2);
                pro2.setSpsx(spsx);

                //找到图片
                List<Photograph> list1 = commodityDao.findAllListByPhotograph(pro2.getFbk1());
                if (list1 != null) {
                    pro2.setPicture(list1.get(0).getPhotographUrl());
                }
            }
            pro.setCreateTimeToString(DateUtils.getTimeDay(pro.getCreateTime()));//时间转换
        }
        return list;
    }

    @Override
    @Transactional
    public Message quantityShipped(ProductOrder productOrder) {
        Message me = new Message();
        for (ProductOrder pro : productOrder.getProductOrderList()) {
            System.out.println("111商品号"+pro.getFbk1()+"数量"+pro.getAmount()+"实发数量"+pro.getRealAmount());
            if (Integer.parseInt(pro.getAmount()) < Integer.parseInt(pro.getRealAmount())) {
                me.setFlag("2");
                me.setMessage("实际发货数量异常");
                return me;
            }
            ProductOrder pp = productOrderDao.getStatus(pro);
            if("6".equals(pp.getOrderStatus())){
                me.setFlag("2");
                me.setMessage("该订单已经核销完成");
                return me;
            }
        }
        String date = DateUtils.getNowTime();
        //若发货数量不是订单数量，回写商品冻结数量
        for (ProductOrder pro : productOrder.getProductOrderList()) {
            //新增实际发货的入库单信息和数量
            //1 查出该商品入库单剩余数量大于0的入库单
            List<RkdDto> rkddtos = productOrderDao.getRkdSl(pro.getFbk1());
            if(rkddtos.size() == 0){
                me.setFlag("2");
                me.setMessage("数据异常，无可用入库单可核销发货的数量！");
                return me;
            }
            //实发数量，当等于0时，入库单选择插表结束
            int realNum = Integer.parseInt(pro.getRealAmount());
            for (RkdDto dto: rkddtos) {
                if(realNum > 0) {
                    //情况1  该入库单剩余数量大于等于实发数量，直接插入表
                    if (Integer.parseInt(dto.getSysl()) >= Integer.parseInt(pro.getRealAmount())) {
                        //插表，然后赋值realNum 为0，让他不继续走逻辑
                        RkdinfoDto rkdto = new RkdinfoDto();
                        rkdto.setRkdNumber(pro.getRealAmount());
                        rkdto.setRkdCode(dto.getTradeName());
                        rkdto.setDdId(String.valueOf(pro.getOrderId()));
                        rkdto.setCreateName(pro.getCreateUser());
                        rkdto.setCreateTime(date);
                        rkdto.setProNumber(pro.getFbk1());
                        productOrderDao.insertRkdinfo(rkdto);
                        realNum = 0;
                    }
                    //情况二 该入库单剩余数量小于实发数量，分批插入表，直到一个入库单剩余数量大于实发数量
                    else {
                        //插表，然后赋值realNum 为剩余数量，让他继续走逻辑
                        RkdinfoDto rkdto = new RkdinfoDto();
                        rkdto.setRkdNumber(dto.getSysl());
                        rkdto.setRkdCode(dto.getTradeName());
                        rkdto.setDdId(String.valueOf(pro.getOrderId()));
                        rkdto.setCreateName(pro.getCreateUser());
                        rkdto.setCreateTime(date);
                        rkdto.setProNumber(pro.getFbk1());
                        productOrderDao.insertRkdinfo(rkdto);

                        realNum = realNum - Integer.parseInt(dto.getSysl());
                    }
                }
            }

            System.out.println("入参商品编号"+pro.getFbk1());
            pro.setFbk4(date);//发货时间
            productOrderDao.updateRealAmount(pro);//实发数量存入

            //商品信息
            Commodity commodity = new Commodity();
            commodity.setCommodityNumber(pro.getFbk1());
            Commodity commodity2 = commodityDao.selectOneCommodity(commodity);

            System.out.println("该商品冻结数量"+commodity2.getFbk3());

            commodity2.setFbk3(Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(pro.getAmount())+"");
            //commodity2.setFbk4(Integer.parseInt(commodity2.getFbk4())-Integer.parseInt(pro.getAmount())+"");
            System.out.println("222商品号"+pro.getFbk1()+"冻结数量"+commodity2.getFbk3()+"数量"+pro.getAmount());
            commodityDao.updateAmount(commodity2);//还原商品冻结数量

            MoveHis moveHis=new MoveHis();
            moveHis.setType("发货解冻");
            moveHis.setCommodityNumber(commodity2.getCommodityNumber());
            moveHis.setNumber(pro.getAmount());
            moveHis.setUserName(productOrder.getOrderNum());
            moveHisDao.save(moveHis);
            //推送消息提醒商品预警信息
            //判断是否需要推送预警信息
            //商品现有库存
            /*String amount = productDao.findSumAmount(pro.getFbk1());
            String realAmount = productOrderDao.findSumRealAmount(pro.getFbk1());
            if(amount == null){ amount="0";}if(realAmount == null){ realAmount="0";}
            int fbk2 = Integer.parseInt(amount)-Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(realAmount);
            if(StringUtils.isEmpty(commodity2.getEarlyWarning())){
                commodity2.setEarlyWarning("0");
            }
            if(fbk2 < Integer.parseInt(commodity2.getEarlyWarning())) {
                weiXinService.sendKunChunYuJing(commodity2,fbk2);
            }*/
        }

        //改订单状态为6，完成核销
        productOrder.setOrderStatus("6");
        productOrderDao.updateStatusByNum(productOrder);
        me.setFlag("1");
        me.setMessage("确认成功");
        return me;
    }

    @Override
    public List<ProductOrder> selectProductOrder(ProductOrder productOrder) {
        productOrder.setOrderStatus("4");
        List<ProductOrder> list =new ArrayList<>();
        if(productOrder.getSf2() == null) {
            list = productOrderDao.selectProductOrder(productOrder);
        }else if("1".equals(productOrder.getSf2())){
            list = productOrderDao.selectProductOrder3(productOrder);
        }else{
            list = productOrderDao.selectProductOrder2(productOrder);
        }
        for (ProductOrder pro: list) {
            for (ProductOrder pro2: pro.getProductOrderList()) {
                //找到图片
                List<Photograph> list1 = commodityDao.findAllListByPhotograph(pro2.getFbk1());
                if (list1 != null) {
                    pro2.setPicture(list1.get(0).getPhotographUrl());
                }
            }
            pro.setCreateTimeToString(DateUtils.getTimeDay(pro.getCreateTime()));//时间转换
        }
        return list;
    }

    @Override
    public List<ProductOrder> findOrderListFinally(ProductOrder productOrder) {
        String orderStatus = "6";
        List<ProductOrder> list =new ArrayList<>();
        if(productOrder.getSf2() == null) {
            list = productOrderDao.findProductOrderList(orderStatus);
        }else if("1".equals(productOrder.getSf2())){
            list = productOrderDao.findProductOrderList3(orderStatus);
        }else{
            list = productOrderDao.findProductOrderList2(orderStatus);
        }
        for (ProductOrder pro: list) {
            for (ProductOrder pro2: pro.getProductOrderList()) {
                Commodity commodity = new Commodity();
                commodity.setCommodityNumber(pro2.getFbk1());
                Commodity commodity2 = commodityDao.selectOneCommodity(commodity);
                //属性拼接
                CommodityServiceImpl co = new CommodityServiceImpl();
                String spsx = co.getPropertyNameTo(commodity2);
                pro2.setSpsx(spsx);

                //找到图片
                List<Photograph> list1 = commodityDao.findAllListByPhotograph(pro2.getFbk1());
                if (list1 != null) {
                    pro2.setPicture(list1.get(0).getPhotographUrl());
                }
            }
            pro.setCreateTimeToString(DateUtils.getTimeDay(pro.getCreateTime()));//时间转换
        }
        return list;
    }

    @Override
    @Transactional
    public Message quantityShipped2(ProductOrder productOrder) {
        Message me = new Message();
        for (ProductOrder pro : productOrder.getProductOrderList()) {
            System.out.println("111商品号"+pro.getFbk1()+"数量"+pro.getAmount()+"实发数量"+pro.getRealAmount());
            ProductOrder pp = productOrderDao.getStatus(pro);
            if("6".equals(pp.getOrderStatus())){
                me.setFlag("2");
                me.setMessage("该订单已经核销完成");
                return me;
            }
        }
        String date = DateUtils.getNowTime();
        //若发货数量不是订单数量，回写商品冻结数量
        for (ProductOrder pro : productOrder.getProductOrderList()) {
            System.out.println("入参商品编号"+pro.getFbk1());
            pro.setFbk4(date);//发货时间
            productOrderDao.updateRealAmount(pro);//实发数量存入

            //商品信息
            Commodity commodity = new Commodity();
            commodity.setCommodityNumber(pro.getFbk1());
            Commodity commodity2 = commodityDao.selectOneCommodity(commodity);

            System.out.println("该商品冻结数量"+commodity2.getFbk3());

            commodity2.setFbk3(Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(pro.getAmount())+"");
            //commodity2.setFbk4(Integer.parseInt(commodity2.getFbk4())-Integer.parseInt(pro.getAmount())+"");
            System.out.println("222商品号"+pro.getFbk1()+"冻结数量"+commodity2.getFbk3()+"数量"+pro.getAmount());
            commodityDao.updateAmount(commodity2);//还原商品冻结数量

            //推送消息提醒商品预警信息
            //判断是否需要推送预警信息
            //商品现有库存
            /*String amount = productDao.findSumAmount(pro.getFbk1());
            String realAmount = productOrderDao.findSumRealAmount(pro.getFbk1());
            if(amount == null){ amount="0";}if(realAmount == null){ realAmount="0";}
            int fbk2 = Integer.parseInt(amount)-Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(realAmount);
            if(StringUtils.isEmpty(commodity2.getEarlyWarning())){
                commodity2.setEarlyWarning("0");
            }
            if(fbk2 < Integer.parseInt(commodity2.getEarlyWarning())) {
                weiXinService.sendKunChunYuJing(commodity2,fbk2);
            }*/
        }

        //改订单状态为6，完成核销
        productOrder.setOrderStatus("6");
        productOrderDao.updateStatusByNum(productOrder);
        me.setFlag("1");
        me.setMessage("确认成功");
        return me;
    }

    @Override
    public List<ProductOrder> findOrderListFinallyByOrderNum(ProductOrder productOrder) {
        productOrder.setOrderStatus("6");
        List<ProductOrder> list =new ArrayList<>();
        if(productOrder.getSf2() == null) {
            list = productOrderDao.selectProductOrder(productOrder);
        }else if("1".equals(productOrder.getSf2())){
            list = productOrderDao.selectProductOrder3(productOrder);
        }else{
            list = productOrderDao.selectProductOrder2(productOrder);
        }
        for (ProductOrder pro: list) {
            for (ProductOrder pro2: pro.getProductOrderList()) {
                //找到图片
                List<Photograph> list1 = commodityDao.findAllListByPhotograph(pro2.getFbk1());
                if (list1 != null) {
                    pro2.setPicture(list1.get(0).getPhotographUrl());
                }
            }
            pro.setCreateTimeToString(DateUtils.getTimeDay(pro.getCreateTime()));//时间转换
        }
        return list;
    }

    @Override
    public List<HrmResource> findAllUserName() {
        List<HrmResource> list = productOrderDao.findAllUserName();
        Collections.sort(list);
        return list;
    }

    @Override
    public List<HrmResource> selectUserName(String code) {
        List<HrmResource> list = productOrderDao.selectUserName(code);
        Collections.sort(list);
        return list;
    }

    @Override
    public int sendEarlyWarning(ProductOrder pro) {
        //推送消息提醒商品预警信息
        //判断是否需要推送预警信息
        //商品现有库存
        Commodity commodity = new Commodity();
        commodity.setCommodityNumber(pro.getFbk1());
        Commodity commodity2 = commodityDao.selectOneCommodity(commodity);
        String amount = productDao.findSumAmount(pro.getFbk1());
        String realAmount = productOrderDao.findSumRealAmount(pro.getFbk1());
        if(amount == null){ amount="0";}if(realAmount == null){ realAmount="0";}
        int fbk2 = Integer.parseInt(amount)-Integer.parseInt(commodity2.getFbk3())-Integer.parseInt(realAmount);
        if(StringUtils.isEmpty(commodity2.getEarlyWarning())){
            commodity2.setEarlyWarning("0");
        }
        if(fbk2 < Integer.parseInt(commodity2.getEarlyWarning())) {
            weiXinService.sendKunChunYuJing(commodity2,fbk2);
        }
        return 123;
    }

    @Autowired
    private MyAsyncTask myAsyncTask;
}
